import {
 getLoanTaskId, createWorkTask, getWorkTask, getLoanStatus
} from '@/api/flow/work';
import { getLimits, getSettingsLimits } from '@/api/risk/user';
import { START_ACTION, AGREE_ACTION } from '@/utils/actions';

const END_NODE_STATUS_NAME = '已结束';
const USER_CONFIRMATION_NODE_STATUS_NAME = '用户确认信息';

export default {
  data() {
    return {
      loading: false,

      // 金额配置
      moneyState: {
        amount: 0,
        stage: 0,
        cost: {
          value: 0,
          prefix: '$',
          connect: ''
        }
      },

      // tid
      tid: '',

       // forms
      formFields: [
        {
          label: '借款金额',
          value: '1', // 1 | 0
          link: '是否可以借款（机审）',
          field: {}
        }
      ]
    };
  },

  computed: {
    loanDisabled() {
      return (this.moneyState.amount <= 0);
        // || !this.authentication
    }
  },

  created() {
    this.authentication ? this.getLimits() : this.getSettingsLimits();
  },

  methods: {
    // 获取风控
    getLimits() {
      return new Promise((resolve, reject) => {
        getLimits()
          .then((data) => {
            // console
            const { amount, charges_free, repay_methods } = data;
            this.moneyState.amount = amount;
            this.moneyState.cost.connect = charges_free;

            if (repay_methods.length) {
              this.moneyState.stage = repay_methods[(repay_methods.length - 1)].day;
            }

            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取配置金额
    getSettingsLimits() {
      return new Promise((resolve, reject) => {
        getSettingsLimits()
          .then((data) => {
            const { max_amount, charges_free, repay_methods } = data;
            this.moneyState.amount = max_amount;
            this.moneyState.cost.connect = charges_free;

            if (repay_methods.length) {
              this.moneyState.stage = repay_methods[(repay_methods.length - 1)].day;
            }
            // moneyState: {
            //   amount: 0,
            //   stage: 0,
            //   cost: 0
            // },
            // const { max_amount, max_days: { way, charges },  } = data;
            // this.moneyState.amount = max_amount;

            // const isRatio = (way === '1');
            // this.moneyState.cost.value = (isRatio ? `${charges * 100}` : charges);
            // this.moneyState.cost.prefix = (isRatio ? `%` : '$');

            // const { value, prefix } = this.moneyState;
            // this.moneyState.cost.connect = isRatio ? `${value} ${prefix}` : `${prefix} ${value}`
            // this.moneyState.stage = repay_methods.length;

            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // loan
    async loan() {
      // this.loanModal.visible = true;
      // 用户认证检查
      const isAuth = this.userAuthCheck();
      if (isAuth) return false;

      this.loading = true;

      // 借款流程发起
      try {
        // await this.getLoanStatus();
        await this.createLoadProccess();
        this.$emit('loan', this.tid);
        // await this.submitLoan();

        // try {
        //   await this.getWorkTaskStatusPromises();
        // } catch (error) {
        //   this.$notification.error({
        //     message: 'Audit failed, please try again later!',
        //     duration: 1,
        //   });

        //   throw Error(error);
        // }

        // this.loading = false;
        // this.loanModal.visible = false;
      } catch (error) {
        console.log(error, 'dadadad');
      } finally {
        this.loading = false;
      }
    },

    // authentication rule
    userAuthCheck() {
      if (!this.authentication) {
        const modalProps = {
          okButtonProps: {
            props: {
              shape: 'round'
            }
          },
          cancelButtonProps: {
            props: {
              shape: 'round'
            }
          }
        };

        const _self = this;

        this.$confirm({
          title: 'Tips',
          content: 'You need to complete your personal information and bank account information to get your loan limit!',
          cancelText: 'Cancel',
          okText: 'To perfect',
          ...modalProps,
          onOk() {
            _self.$router.push({
              name: 'ModifyBasicSettings'
            });
          }
        });

        return true;
        throw new Error();
      }
    },

    // loan status
    async getLoanStatus() {
      try {
        const data = await getLoanStatus();

        return data;
      } catch (error) {
        throw Error(error);
      }
    },

    // 创建借款流程
     async createLoadProccess() {
       try {
         const data = await getLoanTaskId();

         const res = await createWorkTask(data.alias_id);
         this.tid = res.task_id;

         return res;
       } catch (error) {
         throw new Error(error);
       }
    },

    // getWorkTaskStatus
    getWorkTaskStatus() {
      return new Promise((resolve, reject) => {
        getWorkTask(this.tid)
          .then((data) => {
            const isNodeStatus = (data.status_name === END_NODE_STATUS_NAME);
            if (isNodeStatus) {
              reject(data.current_nodes[0]);
              return false;
            }
            resolve(data.current_nodes[0]);
          })
          .catch((error) => reject(error));
      });
    },

    // submitLoan
    submitLoan() {
      return new Promise((resolve, reject) => {
        this.getWorkTask()
          .then(async () => {
            this.submitAction(START_ACTION, this.actionData())
              .then(async (data) => {
                resolve(data);
              })
              .catch((error) => {
                reject(error);
              });
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    getWorkTaskStatusPromises() {
      let i = 0;
      return new Promise((resolve, reject) => {
        const timer = setInterval(async () => {
          i += 1;

          let IS_STATUS = false;
          try {
            const currentNode = await this.getWorkTaskStatus();

            IS_STATUS = (currentNode.name === USER_CONFIRMATION_NODE_STATUS_NAME);
            if (IS_STATUS) {
              window.clearInterval(timer);
              resolve();
            }
          } catch (error) {
            reject(error);
          }
          if (i >= 3) {
            window.clearInterval(timer);
            IS_STATUS ? resolve() : reject();
          }
        }, 2000);
      });
    }
  }
};
